<?php

/**
 * @Author: king
 * @Date:   2019-05-04 16:55:36
 * @Last Modified by:   king
 * @Last Modified time: 2019-05-26 10:55:44
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use Cache;
class LanmeiCounselorExercise extends Base
{
    protected $table = 'counselor_exercise';

    /**
     * 获取当前习题类型下的习题信息id
     * @param int $cid 类型
     * @param int $num 题目数量
     * @return bool|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getExerciseId($cid = 0, $num = 0)
    {
        $ids = false;
        if ($ids === false)
        {
            $where = ['status' => 1, 't_id' => $cid];
            try
            {
                $ids = $this->where($where)->pluck('id');
            }
            catch (\Exception $e)
            {
                throw new ApiException('获取习题失败', config('code.error'));
            }
        }

        if ($num <= count($ids))
        {
            //获取随机的key
            $key = array_rand($ids, $num);
            //获取随机后的习题id
            foreach ($key as $v)
            {
                $arr[] = $ids[$v];
            }
        } else
        {
            $arr = $ids;
        }

        $data = $this->getExerciseInfo($arr, $cid);

        return $data;
    }

    /**
     * 批量获取习题信息
     * @param array $ids
     */
    public function getExerciseInfo($ids = [], $pid = 0)
    {
        $data = false;

        if ($data === false) {
            if (is_array($ids) && $ids)
            {
                $where = [['id','in', $ids], 't_id' => $pid];
            } else
            {
                $where = ['id' => $ids, 't_id' => $pid];
            }
            try {
                $data = $this->select('id','title','title_img','option_a','option_b','option_c','option_d','answer','option_type')->where($where)->get();
                $data = json_decode(json_encode($data, true), true);
            } catch (\Exception $e) {
                throw new ApiException('获取习题失败', config('code.error'));
            }
        }

        return $data;
    }

}